//
//  YCScanFollowViewController.m
//  YCSchool
//
//  Created by Yanglixia on 16/5/11.
//  Copyright © 2016年 yanglinxia. All rights reserved.
//  扫描二维码

#import "YCScanFollowViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <CoreLocation/CoreLocation.h>
#import <ZXingObjC/ZXMultiFormatReader.h>
#import <ZXingObjC/ZXCGImageLuminanceSource.h>
#import <ZXingObjC/ZXHybridBinarizer.h>
#import <ZXingObjC/ZXBinaryBitmap.h>
#import <ZXingObjC/ZXDecodeHints.h>
#import <ZXingObjC/ZXResult.h>
#import "YCMyQRCodeViewController.h"

@interface YCScanFollowViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    NSString *_suppliersId;
    NSString *_statusStr;
}
@property (nonatomic, strong) AVCaptureSession *qrSession;//会话
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *qrVideoPreviewLayer;//读取
@property (nonatomic, strong) UIImageView *line;//交互线
@property (nonatomic, strong) NSTimer *lineTimer;//交互线控制
@property (nonatomic, strong) NSString *supller_id;

/** 从相册中选择 */
@property (nonatomic, strong) UIButton *selectQRCodeFromPhotoBtn;
/** 我的二维码 */
@property (nonatomic, strong) UIButton *myQRCodeBtn;

@property (nonatomic, assign, readonly) CGFloat kLineMinY;
@property (nonatomic, assign, readonly) CGFloat kLineMaxY;
@property (nonatomic, assign, readonly) CGFloat kReaderViewWidth;
@property (nonatomic, assign, readonly) CGFloat kReaderViewHeight;

@end

@implementation YCScanFollowViewController
@synthesize kLineMinY = _kLineMinY;
@synthesize kLineMaxY = _kLineMaxY;
@synthesize kReaderViewWidth = _kReaderViewWidth;
@synthesize kReaderViewHeight = _kReaderViewHeight;

#pragma mark - 属性获取方法
- (CGFloat)kLineMinY
{
    if (!_kLineMinY) {
        _kLineMinY = (self.view.yc_height - 200) / 2.0 - 64;
    }
    return _kLineMinY;
}

- (CGFloat)kLineMaxY
{
    if (!_kLineMaxY) {
        _kLineMaxY = (self.view.yc_height - 200) / 2.0 + 200 - 64;
    }
    return _kLineMaxY;
}

- (CGFloat)kReaderViewWidth
{
    if (!_kReaderViewWidth) {
        _kReaderViewWidth = 200;
    }
    return _kReaderViewWidth;
}

- (CGFloat)kReaderViewHeight
{
    if (!_kReaderViewHeight) {
        _kReaderViewHeight = 200;
    }
    return _kReaderViewHeight;
}

#pragma mark - 视图控制器生命周期

- (void)dealloc
{
    if (_qrSession) {
        [_qrSession stopRunning];
        _qrSession = nil;
    }
    
    if (_qrVideoPreviewLayer) {
        _qrVideoPreviewLayer = nil;
    }
    
    if (_line) {
        _line = nil;
    }
    
    if (_lineTimer)
    {
        [_lineTimer invalidate];
        _lineTimer = nil;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = NSLocalizedString(@"扫一扫", nil);
    [self yc_addBackBarButtonItemWithTarget:self action:@selector(didTouchUpInsideBackBarButtonItem:)];
    
    [self initUI];
    [self setOverlayPickerView];
    [self startSYQRCodeReading];
    YCLogFunc
}

#pragma mark - 自定义的方法

- (void)initUI
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //摄像头判断
    NSError *error = nil;
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
    
    if (error)
    {
        YCLog(@"没有摄像头-%@", error.localizedDescription);
        
        return;
    }
    
    //设置输出(Metadata元数据)
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    //设置输出的代理
    //使用主线程队列，相应比较同步，使用其他队列，相应不同步，容易让用户产生不好的体验
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    //设置感兴趣区域(有效扫描区)
    [output setRectOfInterest:[self getReaderViewBoundsWithSize:CGSizeMake(self.kReaderViewWidth, self.kReaderViewHeight)]];
    
    CGRect rect = [self getReaderViewBoundsWithSize:CGSizeMake(200, 200)];
    
    //拍摄会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    
    // 读取质量，质量越高，可读取小尺寸的二维码
//    if ([session canSetSessionPreset:AVCaptureSessionPreset1920x1080])
//    {
//        [session setSessionPreset:AVCaptureSessionPreset1920x1080];
//    }
//    else if ([session canSetSessionPreset:AVCaptureSessionPreset1280x720])
//    {
//        [session setSessionPreset:AVCaptureSessionPreset1280x720];
//    }
//    else
//    {
//        [session setSessionPreset:AVCaptureSessionPresetPhoto];
//    }
    
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([session canAddInput:input])
    {
        [session addInput:input];
    }
    
    if ([session canAddOutput:output])
    {
        [session addOutput:output];
    }
    
    //设置输出的格式
    //一定要先设置会话的输出为output之后，再指定输出的元数据类型
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];//output.availableMetadataObjectTypes
    
    //设置预览图层
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:session];
    
    //设置preview图层的属性
    //preview.borderColor = [UIColor redColor].CGColor;
    //preview.borderWidth = 1.5;
    [preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    
    //设置preview图层的大小
    preview.frame = CGRectMake((self.view.yc_width-self.kReaderViewWidth)/2.0, self.kLineMinY, 200, 200);//self.view.layer.bounds;
    //[preview setFrame:CGRectMake(0, 0, kDeviceWidth, KDeviceHeight)];
    CGRect fr = self.view.layer.frame;
    //将图层添加到视图的图层
    
    [self.view.layer insertSublayer:preview atIndex:0];
    //[self.view.layer addSublayer:preview];
    self.qrVideoPreviewLayer = preview;
    self.qrVideoPreviewLayer.backgroundColor = [UIColor colorWithWhite:1 alpha:1].CGColor;
    self.qrSession = session;
}

// 相反方向,以右上角为圆点
- (CGRect)getReaderViewBoundsWithSize:(CGSize)asize
{
    return CGRectMake(self.kLineMinY / self.view.yc_height, ((self.view.yc_width - asize.width) / 2.0) / self.view.yc_width, asize.height / self.view.yc_height, asize.width / self.view.yc_width );
}

- (void)setOverlayPickerView
{
    UIView *scanCropView = [[UIView alloc] initWithFrame:CGRectMake(
        (kScreenWidth - self.kReaderViewWidth) / 2.0-1,
        self.kLineMinY,
        self.kReaderViewWidth+ 1,
        self.kReaderViewHeight + 1)];
    scanCropView.layer.borderColor = [UIColor yc_colorWithUInt:0xddcdcd].CGColor;
    scanCropView.layer.borderWidth = 1.0;
//    scanCropView.backgroundColor = [UIColor redColor];
    [self.view addSubview:scanCropView];
    
    //画中间的基准线
    _line = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - 200) / 2.0, self.kLineMinY, 200, 12 * 300 / 320.0)];
    [_line setImage:[UIImage imageNamed:@"register_centerLine"]];
    [self.view addSubview:_line];
    
    //最上部view
    UIView* upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, self.kLineMinY)];//80
    upView.alpha = 1;
    upView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:upView];
    
    //左侧的view
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, self.kLineMinY, (kScreenWidth - self.kReaderViewWidth) / 2.0, self.kReaderViewHeight)];
    leftView.alpha = 1;
    leftView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:leftView];
    
    //右侧的view
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth - CGRectGetMaxX(leftView.frame), self.kLineMinY, CGRectGetMaxX(leftView.frame), self.kReaderViewHeight)];
    rightView.alpha = 1;
    rightView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:rightView];
    
    CGFloat space_h = kScreenHeight - self.kLineMaxY;
    
    //底部view
    UIView *downView = [[UIView alloc] initWithFrame:CGRectMake(0, self.kLineMaxY, kScreenWidth, space_h)];
    downView.alpha = 1;
    downView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:downView];
    
    //四个边角
    UIImage *cornerImage = [UIImage imageNamed:@"register_leftTop"];
    
    //左侧的view
    UIImageView *leftView_image = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftView.frame) - 0.5, self.kLineMinY, cornerImage.size.width, cornerImage.size.height)];
    leftView_image.image = cornerImage;
    [self.view addSubview:leftView_image];
    
    cornerImage = [UIImage imageNamed:@"register_rightTop"];
    
    //右侧的view
    UIImageView *rightView_image = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMinX(rightView.frame) - cornerImage.size.width + 1, self.kLineMinY, cornerImage.size.width, cornerImage.size.height)];
    rightView_image.image = cornerImage;
    [self.view addSubview:rightView_image];
    
    cornerImage = [UIImage imageNamed:@"register_leftBottom"];
    
    //底部view
    UIImageView *downView_image = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftView.frame) - 0.5, CGRectGetMinY(downView.frame) - cornerImage.size.height + 1, cornerImage.size.width, cornerImage.size.height)];
    downView_image.image = cornerImage;
    //downView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:downView_image];
    
    cornerImage = [UIImage imageNamed:@"register_rightBottom"];
    
    UIImageView *downViewRight_image = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMinX(rightView.frame) - cornerImage.size.width + 1, CGRectGetMinY(downView.frame) - cornerImage.size.height + 1, cornerImage.size.width, cornerImage.size.height)];
    downViewRight_image.image = cornerImage;
    //downView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:downViewRight_image];
    
    //说明label
    UILabel *labIntroudction = [[UILabel alloc] init];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.frame = CGRectMake(CGRectGetMaxX(leftView.frame), CGRectGetMinY(downView.frame) + 25, self.kReaderViewWidth, 20);
    labIntroudction.textAlignment = NSTextAlignmentCenter;
    labIntroudction.font = [UIFont boldSystemFontOfSize:11.0];
    labIntroudction.textColor = [UIColor grayColor];
    labIntroudction.text = @"将二维码对入取景框,即可自动扫描";
    [self.view addSubview:labIntroudction];
    
    UIButton *selectQRCodeFromPhotoBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, kScreenHeight - 80-64, 120, 35)];
    selectQRCodeFromPhotoBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    selectQRCodeFromPhotoBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [selectQRCodeFromPhotoBtn setTitle:@"从相册选择" forState:UIControlStateNormal];
    [selectQRCodeFromPhotoBtn setImage:[UIImage imageNamed:@"从相册选择"] forState:UIControlStateNormal];
    [selectQRCodeFromPhotoBtn addTarget:self action:@selector(selectQRCodeFromPhotoBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [selectQRCodeFromPhotoBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    self.selectQRCodeFromPhotoBtn = selectQRCodeFromPhotoBtn;
    [self.view addSubview:selectQRCodeFromPhotoBtn];
    
    UIButton *myQRCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(kScreenWidth-20-130, kScreenHeight - 80-64, 120, 35)];
    myQRCodeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    myQRCodeBtn.titleEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    [myQRCodeBtn setTitle:@"我的二维码" forState:UIControlStateNormal];
    [myQRCodeBtn setImage:[UIImage imageNamed:@"我的二维码"]forState:UIControlStateNormal];
    [myQRCodeBtn addTarget:self action:@selector(myQRCodeBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [myQRCodeBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    self.myQRCodeBtn = myQRCodeBtn;
    [self.view addSubview:myQRCodeBtn];
    
}


#pragma mark -
#pragma mark 输出代理方法
//此方法是在识别到QRCode，并且完成转换
//如果QRCode的内容越大，转换需要的时间就越长
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //扫描结果
    if (metadataObjects.count > 0)
    {
//        [self stopSYQRCodeReading];
        
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        
        if (obj.stringValue && ![obj.stringValue isEqualToString:@""] && obj.stringValue.length > 0)
        {
            if (!obj.stringValue)
            {
                [SVProgressHUD showErrorWithStatus:@"未获取到Id..."];
                return;
            }
            
            YCLog(@"%@",obj.stringValue);
            
            if([obj.stringValue hasPrefix:@"orderToken"])
            {
//                if ([GOLoginUser loginUser].userType == GOLoginUserTypeNormal)
//                {
//                    [SVProgressHUD showErrorWithStatus:@"用户无法确认消费订单"];
//                    [self.navigationController popViewControllerAnimated:YES];
//                    return;
//                }
                
                NSArray *objs = [obj.stringValue componentsSeparatedByString:@"orderToken="];
                
//                @go_weakify(self);
//                
//                GOWebServiceSuccessCallBack success = ^(AFHTTPRequestOperation *operation, GOWebServiceResponse *response) {
//                    if(response.success)
//                    {
//                        @go_strongify(self);
//                        if (!self) return ;
//                        
//                        [SVProgressHUD showSuccessWithStatus:@"商品消费成功"];
//                        [self.navigationController popViewControllerAnimated:YES];
//                        
//                    }
//                };
//                
//                GOWebServiceFailureCallBack failure = ^(AFHTTPRequestOperation *operation, NSError *error) {
//                    
//                };
//                
//                [[GOWebService service] postAction:GOAPIOrdersConfirmConsum
//                                            params:@{@"orderToken":objs.lastObject}
//                                           success:success
//                                           failure:failure];
            }
            else
            {
                if ([self.delegate respondsToSelector:@selector(selectScanFollowViewControllerCancel:didSuccessScanId:)])
                {
                    [self.delegate selectScanFollowViewControllerCancel:self didSuccessScanId:obj.stringValue];
                }
            }
            
        }
    }
    else
    {
//        if (self.YCScanFollowFailBlock) {
//            self.YCScanFollowFailBlock(self);
//            self.YCScanFollowFailBlock = ^(YCScanFollowViewController *aqrvc){
//                [aqrvc dismissViewControllerAnimated:NO completion:nil];
//            };
//        }
    }
}
#pragma mark -
#pragma mark 交互事件

- (void)startSYQRCodeReading
{
    _lineTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 / 20 target:self selector:@selector(animationLine) userInfo:nil repeats:YES];
    
    [self.qrSession startRunning];
    
    YCLog(@"start reading");
}

- (void)stopSYQRCodeReading
{
    if (_lineTimer)
    {
        [_lineTimer invalidate];
        _lineTimer = nil;
    }
    
    [self.qrSession stopRunning];
    
    YCLog(@"stop reading");
}

///返回按钮
- (void)didTouchUpInsideBackBarButtonItem:(UIBarButtonItem *)item
{
    if ([self.delegate respondsToSelector:@selector(selectScanFollowViewControllerCancel:didSuccessScanId:)])
    {
        [self.delegate selectScanFollowViewControllerCancel:self didSuccessScanId:@""];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark 上下滚动交互线

- (void)animationLine
{
    __block CGRect frame = _line.frame;
    
    static BOOL flag = YES;
    
    if (flag)
    {
        frame.origin.y = self.kLineMinY;
        flag = NO;
        
        [UIView animateWithDuration:1.0 / 20 animations:^{
            
            frame.origin.y += 5;
            _line.frame = frame;
            
        } completion:nil];
    }
    else
    {
        if (_line.frame.origin.y >= self.kLineMinY)
        {
            if (_line.frame.origin.y >= self.kLineMaxY - 12)
            {
                frame.origin.y = self.kLineMinY;
                _line.frame = frame;
                
                flag = YES;
            }
            else
            {
                [UIView animateWithDuration:1.0 / 20 animations:^{
                    
                    frame.origin.y += 5;
                    _line.frame = frame;
                    
                } completion:nil];
            }
        }
        else
        {
            flag = !flag;
        }
    }
    
    //NSLog(@"_line.frame.origin.y==%f",_line.frame.origin.y);
}

#pragma mark - 点击事件
- (void)selectQRCodeFromPhotoBtnClick:(UIButton *)button
{
    YCLogFunc
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
//    imagePicker.go_integerIdentifier = GOIndexSelectStatusScan;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
- (void)myQRCodeBtnClick:(UIButton *)button
{
    YCLogFunc
    YCMyQRCodeViewController *myQRCodeVc = [[YCMyQRCodeViewController alloc] init];
    [self.navigationController pushViewController:myQRCodeVc animated:YES];
}

// 添加图片
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    /********** 利用探测器读取,可读到 ********/
    // 1.取得图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    // 2.转成CIImage
    CIImage *CIImageObj = [CIImage imageWithCGImage:image.CGImage];
    
    // 3.创建一个探测器
    CIContext *context = [CIContext contextWithOptions:nil];
    NSDictionary *dict = @{CIDetectorAccuracy:CIDetectorAccuracyHigh};
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:context options:dict];
    // 4.利用探测器探测结果
    NSArray *features = [detector featuresInImage:CIImageObj];
    
    // 5.取出结果
    for (CIQRCodeFeature *result in features) {
        
        // 打印结果
        NSLog(@"messageString:%@",result.messageString);
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:result.messageString]];
    }
    // 只要实现代理方法, 就需要我们自己手动关闭浏览器
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    return;
    
    /******* 利用zxing读不出来 ****/
    UIImage *img = [info objectForKey:UIImagePickerControllerOriginalImage];
    if(!img)
    {
        [picker dismissViewControllerAnimated:YES completion:nil];
        return;
    }
//    if(img.imageOrientation != UIImageOrientationUp)
//    {
//        UIGraphicsBeginImageContext(img.size);
//        [img drawAtPoint:CGPointZero];
//        img = UIGraphicsGetImageFromCurrentImageContext();
//        UIGraphicsEndImageContext();
//    }

    CGImageRef imageToDecode = img.CGImage; // Given a CGImage in which we are looking for barcodes
    ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];
    ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
    
    NSError *error = nil;
    ZXDecodeHints *hints = [ZXDecodeHints hints];
    
    ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
    ZXResult *result = [reader decode:bitmap hints:hints error:&error];
    
    YCLog(@"读取结果;%@",result.text);
    
    [picker dismissViewControllerAnimated:YES completion:NULL];
    
//    if (result)
//    {
//        NSString *contents = result.text;
//        
//        if([contents hasPrefix:@"http://www.gonecn.com/newsoft/down.html"])
//        {
//            _scanStatusStr = [contents go_paramOfName:@"type"];
//            _scanSupplierId = [contents go_paramOfName:@"id"];
//        }
//        else
//        {
//            NSArray *objs = [contents componentsSeparatedByString:@"#"];
//            _scanStatusStr = objs.lastObject;
//            _scanSupplierId = objs.firstObject;
//        }
//        [self loadData];
//        DDLogVerbose(@"%@",contents);
//    }
//    else
//    {
//        [SVProgressHUD showErrorWithStatus:@"二维码图片不正确"];
//        return;
//    }
//    
    
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
}


@end
